package com.cloudcreativity.blyg.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;

import com.cloudcreativity.blyg.R;
import com.cloudcreativity.blyg.base.BaseDialogImpl;
import com.cloudcreativity.blyg.databinding.LayoutDialogAddGoodsBinding;
import com.cloudcreativity.blyg.entity.BaseStringResult;
import com.cloudcreativity.blyg.entity.FindGoods;
import com.cloudcreativity.blyg.sqlite.CategoryOne;
import com.cloudcreativity.blyg.sqlite.CategoryTwo;
import com.cloudcreativity.blyg.sqlite.Goods;
import com.cloudcreativity.blyg.sqlite.utils.CategoryDaoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class AddGoodsUtils extends Dialog {

    private Long id = 0L;
    private Integer brandId = 0;
    private Integer unitId = 0;
    public ObservableField<String> name = new ObservableField<>();
    public ObservableField<String> code = new ObservableField<>();
    public ObservableField<String> brand = new ObservableField<>();
    public ObservableField<String> space = new ObservableField<>();
    public ObservableField<String> price = new ObservableField<>();
    public ObservableField<String> unit = new ObservableField<>();
    public ObservableField<String> stock = new ObservableField<>();
    public ObservableField<String> category = new ObservableField<>();

    private CategoryOne cateOne;
    private CategoryTwo cateTwo;

    private OnOkListener onOkListener;

    //远程商品有关
    private BaseDialogImpl baseDialog;
    private CategoryDaoUtils categoryDaoUtils;
    private ScanGunHelper scanGunHelper;

    public void setOnOkListener(OnOkListener onOkListener) {
        this.onOkListener = onOkListener;
    }

    public AddGoodsUtils(@NonNull Context context, String code, BaseDialogImpl baseDialog) {
        super(context, R.style.myProgressDialogStyle);
        this.baseDialog = baseDialog;
        categoryDaoUtils = new CategoryDaoUtils(context);
        setCanceledOnTouchOutside(false);
        setCancelable(true);
        this.code.set(code);
        final LayoutDialogAddGoodsBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context),
                R.layout.layout_dialog_add_goods,
                null,false);
        binding.setUtils(this);
        setContentView(binding.getRoot());

        binding.etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(editable) && editable.length()>=13){
                    //就是商品条码，优先从服务器查询
                    queryGoods(editable.toString());
                }
            }
        });

        scanGunHelper = new ScanGunHelper(new ScanGunHelper.OnScanValueListener() {
            @Override
            public void onScanValue(String value) {
                if(!TextUtils.isEmpty(value) && value.length()>=13){
                    binding.etCode.setText(value);
                }
            }
        });

    }

    @Override
    public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
        if(event.getDeviceId()==-1){
            //系统输入，不是扫码枪输入
            return super.dispatchKeyEvent(event);
        }
        scanGunHelper.analysisKeyEvent(event);
        return true;
    }

    private void queryGoods(final String barCode){
        LogUtils.e("xuxiwu","查询商品一次");
        baseDialog.showProgress("请稍后...");
        HttpUtils.getInstance().findGoods(barCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<FindGoods>(baseDialog,false) {
                    @Override
                    public void onSuccess(FindGoods t) {
                        if(null==t||null==t.getInfo()||t.getInfo().getId()<=0){
                            //说明远程数据库中没有该商品,通过第三方聚合接口查询
                            HttpUtils.getInstance().queryGoods(AppConfig.GOODS_QUERY_KEY,barCode)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new DefaultObserver<BaseStringResult>(baseDialog,false) {
                                        @Override
                                        public void onSuccess(BaseStringResult t) {
                                            baseDialog.dismissProgress();
                                            try {
                                                JSONObject object = new JSONObject(t.getInfo());
                                                if(!"success".equals(object.getString("reason"))){
                                                    ToastUtils.showShortToast(getContext(),"查询商品失败，请手动输入");
                                                }else{
                                                    JSONObject result = object.getJSONObject("result");
                                                    name.set(result.getString("title"));
                                                    price.set(String.valueOf(
                                                            StrUtils.get2BitDecimal(
                                                                    Float.parseFloat(result.getString("price"))
                                                            )
                                                    ));
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                                ToastUtils.showShortToast(getContext(),"查询商品失败，请手动输入");
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            baseDialog.dismissProgress();
                                            ToastUtils.showShortToast(getContext(),"查询商品失败，请手动输入");
                                        }
                                    });
                        }else{
                            //远程数据库中存在该商品,直接展示出来
                            baseDialog.dismissProgress();
                            id = t.getInfo().getId();
                            unitId = t.getInfo().getUnitId();
                            brandId = t.getInfo().getBrandId();
                            name.set(t.getInfo().getName());
                            code.set(t.getInfo().getBarCode());
                            brand.set(t.getInfo().getBrandName());
                            space.set(t.getInfo().getSpecName());
                            price.set(String.valueOf(
                                    StrUtils.get2BitDecimal(t.getInfo().getPrice()/100f)
                            ));
                            unit.set(t.getInfo().getUnit());
                            //根据id查询处一个分类和二级分类
                            CategoryOne cateOneById = categoryDaoUtils
                                    .getCateOneById(t.getInfo().getCategoryOneId());
                            CategoryTwo cateTwoById = categoryDaoUtils
                                    .getCateTwoById(t.getInfo().getCategoryTwoId());
                            cateOne = cateOneById;
                            cateTwo = cateTwoById;
                            category.set(cateOne.getName()+"/"+cateTwo.getName());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        baseDialog.dismissProgress();
                    }
                });
    }

    public void onOk(){
        if(TextUtils.isEmpty(name.get())){
            ToastUtils.showShortToast(getContext(),"名称不能为空");
            return;
        }
        if(null == cateOne || null == cateTwo){
            ToastUtils.showShortToast(getContext(),"分类不能为空");
            return;
        }
        if(TextUtils.isEmpty(code.get())){
            ToastUtils.showShortToast(getContext(),"条码不能为空");
            return;
        }
//        if(TextUtils.isEmpty(brand.get())){
//            ToastUtils.showShortToast(getContext(),"品牌不能为空");
//            return;
//        }
//        if(TextUtils.isEmpty(space.get())){
//            ToastUtils.showShortToast(getContext(),"规格不能为空");
//            return;
//        }
        if(TextUtils.isEmpty(price.get())){
            ToastUtils.showShortToast(getContext(),"价格不能为空");
            return;
        }
//        if(TextUtils.isEmpty(name.get())){
//            ToastUtils.showShortToast(getContext(),"单位不能为空");
//            return;
//        }

        Goods goods = new Goods();
        int sellPrice = new BigDecimal(price.get()).multiply(new BigDecimal(100)).intValue();
        double stockNum = TextUtils.isEmpty(stock.get())?0:Double.parseDouble(stock.get());
        goods.setId(id);
        goods.setBrandId(brandId);
        goods.setUnitId(unitId);
        goods.setIsShelf(0);
        goods.setName(name.get());
        goods.setPrice(sellPrice);
        goods.setBarCode(code.get());
        goods.setBrandName(brand.get());
        goods.setUnit(unit.get());
        goods.setCategoryOneId(cateOne.getId());
        goods.setCategoryTwoId(cateTwo.getId());
        goods.setSpecName(space.get());
        goods.setStock(stockNum);
        if(onOkListener!=null){
            onOkListener.onOk(goods);
        }
        KeyBoardHelper.close(getContext(),this);
        dismiss();
    }

    public interface OnOkListener{
        void onOk(Goods goods);
    }

    public void onCategoryClick(){
        CategoryDialog categoryDialog = new CategoryDialog(getContext());
        categoryDialog.setOnOkListener(new CategoryDialog.OnOkListener() {
            @Override
            public void onOk(CategoryOne one, CategoryTwo two) {
                cateOne = one;
                cateTwo = two;
                category.set(one.getName()+"/"+two.getName());
            }
        });
        categoryDialog.show();
    }

    public void onClose(){

        KeyBoardHelper.close(getContext(),this);
        dismiss();
    }
}
